package com.example.forum.controller;

import com.example.forum.commen.AppResult;
import com.example.forum.commen.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.ArticleReply;
import com.example.forum.model.User;
import com.example.forum.services.IArticleReplyService;
import com.example.forum.services.IArticleService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//回复接口
@RestController
@RequestMapping("/reply")
public class ArticleReplayController {
    private static final Logger log = LoggerFactory.getLogger(ArticleReplayController.class);
    @Resource
    private IArticleService articleService;
    @Resource
    private IArticleReplyService articleReplyService;

    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @RequestParam("articleId") @NonNull Long articleId,
                            @RequestParam("content") @NonNull String content){
        //获取用户
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        //是否禁言
        if(user == null || user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //获取回复帖子对象
        Article article = articleService.selectById(articleId);
        //是否存在或者删除
        if(article == null || article.getDeleteState() == 1) {
            //已删除或者不存在
            return AppResult.failed(ResultCode.FAILED_ARTICLENOT_EXISTS);
        }
        ///是否封帖
        if(article.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        ArticleReply articleReplay = new ArticleReply();
        articleReplay.setArticleId(articleId);//要回复的帖子id
        articleReplay.setPostUserId(user.getId());
        articleReplay.setContent(content);
        //写入回复
        articleReplyService.create(articleReplay);
        //返回结果
        return AppResult.success();
    }

    @GetMapping("/getReply")
    public AppResult<List<ArticleReply>> getReplyArticleId (@RequestParam("articleId") @NonNull Long articleId) {
        //校验帖子是否存在
        Article article = articleService.selectById(articleId);
        if(article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLENOT_EXISTS);
        }
        //调用service
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
        //返回结构
        return AppResult.success(articleReplies);
    }
}
